<template>
  <view class="page">
    <view class="section">
      <button @click="downloadImage">下载网络图片并显示</button>
      <view v-if="progress !== null" class="progress">下载进度：{{ progress }}%</view>
      <image v-if="downloadedImage" :src="downloadedImage" mode="widthFix" class="preview"></image>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      downloadedImage: "",
      progress: null,
      imageUrl: "https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg"
    };
  },
  methods: {
    downloadImage() {
      this.downloadedImage = "";
      this.progress = 0;
      const task = uni.downloadFile({
        url: this.imageUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            this.downloadedImage = res.tempFilePath;
            this.progress = 100;
            uni.showToast({
              title: '下载成功',
              icon: 'success'
            });
            uni.previewImage({ urls: [res.tempFilePath] });
          } else {
            uni.showToast({
              title: '下载失败，状态码：' + res.statusCode,
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error("下载失败：", err);
          uni.showToast({
            title: '下载失败',
            icon: 'none'
          });
        }
      });

      // 监听下载进度
      task.onProgressUpdate((res) => {
        this.progress = res.progress;
        console.log(`下载进度：${res.progress}%`);
      });
    }
  }
};
</script>

<style>
.page {
  padding: 30rpx;
}
.section {
  margin-bottom: 40rpx;
}
.preview {
  width: 100%;
  margin-top: 20rpx;
  border-radius: 10rpx;
}
.progress {
  margin-top: 20rpx;
  text-align: center;
  font-size: 26rpx;
  color: #007AFF;
  font-weight: bold;
}
</style>